package com.example.module_motorcircle.dialog

import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.example.module_motorcircle.R
import com.example.module_motorcircle.databinding.DialogMoreActionBinding

/**
 * @author yaotianxue
 * @description 自定义更多对话框
 * @date 2025/2/13
 */
class MoreActionDialog(
    private val action1:String = "",
    private val action2:String = "",
    private val showAction1:Boolean = true,
    private val showAction2:Boolean = true,
    private val onClickAction1:(()->Unit)? = null,
    private val onClickAction2:(()->Unit)? = null,
): DialogFragment() {
    private lateinit var mParentView: View
    private lateinit var mBinding: DialogMoreActionBinding
    companion object {
        val TAG: String = MoreActionDialog::class.java.simpleName
    }
    //创建
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.MoreActionDialog)
    }
    /**
     * 调整对话框的宽高和位置
     */
    override fun onStart() {
        super.onStart()
        //获得对话框的属性
        val window = dialog?.window
        val attributes = window?.attributes
        //获得窗口的宽度和高度
        val dm = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getMetrics(dm)
        window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
        //修改对话框的属性并重新设置给当前对话框
        attributes?.width = dm.widthPixels
        attributes?.gravity = Gravity.BOTTOM
        window?.attributes = attributes
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DialogMoreActionBinding.inflate(inflater,container,false)
        mParentView = mBinding.root
        return mParentView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        mBinding.tvAction1.apply {
            text = action1
            visibility  = if(showAction1) View.VISIBLE else View.GONE
            setOnClickListener {
                onClickAction1?.invoke()
                dismiss()
            }
        }

        mBinding.tvAction2.apply {
            text = action2
            visibility  = if(showAction2) View.VISIBLE else View.GONE
            setOnClickListener {
                onClickAction2?.invoke()
                dismiss()
            }
        }
        mBinding.tvCancel.setOnClickListener {
            dismiss()
        }

    }

    /**
     * 打开对话框
     */
    fun show(fragmentManager: FragmentManager){
        if(fragmentManager.findFragmentByTag(TAG)?.isVisible === true){
            return
        }
        this.show(fragmentManager, TAG)
    }




}